//
//  NSObject+MOSwizzleMethod.m
//  WCImApp
//
//  Created by MOiMac on 2019/8/30.
//  Copyright © 2019 WCImApp. All rights reserved.
//

#import "NSObject+MOSwizzleMethod.h"
#import <objc/runtime.h>

@implementation NSObject (MOSwizzleMethod)

- (void)swizzleMethod:(SEL)originalSelector swizzledSelector:(SEL)swizzledSelector {
    Class class = [self class];
    
    Method originalMethod = class_getInstanceMethod(class, originalSelector);
    Method swizzledMethod = class_getInstanceMethod(class, swizzledSelector);
    
    BOOL didAddMethod = class_addMethod(class,
                                        originalSelector,
                                        method_getImplementation(swizzledMethod),
                                        method_getTypeEncoding(swizzledMethod));
    
    if (didAddMethod) {
        class_replaceMethod(class,
                            swizzledSelector,
                            method_getImplementation(originalMethod),
                            method_getTypeEncoding(originalMethod));
    } else {
        method_exchangeImplementations(originalMethod, swizzledMethod);
    }
}

+ (void)swizzleInstanceMethodWithClass:(Class)swizzleClass originalSel:(SEL)originalSel swizzledSel:(SEL)swizzledSel {
    Method original = class_getInstanceMethod(swizzleClass, originalSel);
    Method swizzled = class_getInstanceMethod(swizzleClass, swizzledSel);
    method_exchangeImplementations(original, swizzled);
}

+ (void)swizzleClassMethodWithClass:(Class)swizzleClass originalSel:(SEL)originalSel swizzledSel:(SEL)swizzledSel {
    Method original = class_getClassMethod(swizzleClass, originalSel);
    Method swizzled = class_getClassMethod(swizzleClass, swizzledSel);
    method_exchangeImplementations(original, swizzled);
}


- (id)forwardingTargetForSelector:(SEL)aSelector {
    if(aSelector == @selector(length)) return @"";
    if(aSelector == @selector(count)) return @[];
    return nil;
}

@end
